import React from 'react';
import { Layout, Breadcrumb, Icon, Button, Table, Checkbox, Modal, Input, Select, Form, Pagination, message, TreeSelect, Tree } from 'antd';
import { Link } from 'react-router';
import './frontAndBack.less';
import $ from 'jquery';
import Config from '../../common/config';

const FormItem = Form.Item;
const config = new Config();
const { Header, Content, Footer, Sider } = Layout;
const TreeNode = Tree.TreeNode;
const InputGroup = Input.Group;
const Option = Select.Option;
const token = sessionStorage.getItem('token')

class frontAndBackForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tree: [], // 后端分类树数据
            list: [], // 后端分类列表
            showTree: [], // 前端分类树数据
            showList: [], // 前端分类列表
            addVisible: false, // 新增模态框显示
            firstList: [], // 前端一级分类
            firstValue: undefined, // 前端一级分类值
            secondList: [], // 前端二级分类
            secondListShow: [], // 前端二级分类显示
            secondValue: undefined, // 前端二级分类值
            threeList: [], // 前端三级分类
            threeListShow: [], // 前端三级分类显示
            threeValue: undefined, // 前端三级分类值
            checkedKeys: [], // 选中的后端分类
            showCheckedKeys: [], // 选中的前端分类
            relationList: [], // 分类对应关系列表
            expandedKeys: [], // 后端分类展开的节点
            tableList: [], // 表格分类对应关系列表
            publicState: '', // 公共模态框状态
            publicVisible: false, // 公共模态框显示
            selectedRowKeys: [], // 当前选中的复选框
            updateVisible: false, // 修改模态框显示
            showExpandedKeys: [], // 前端分类展开的节点
        }
    }

    componentDidMount() {
        this.getShowCategoryList()
        this.getRelationCategoriesList()
    }

    // 获取前端分类列表
    getShowCategoryList() {
        $.ajax({
            url: `${config.JuseProduct}/categories/getShowCategoryList`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            success: res => {
                console.log('获取前端分类列表', res)
                if (res.code === 200) {
                    const firstList = []
                    const secondList = []
                    const threeList = []
                    res.data.forEach(item => {
                        if (item.level === 1) {
                            firstList.push(item)
                        } else if (item.level === 2) {
                            secondList.push(item)
                        } else if (item.level === 3) {
                            threeList.push(item)
                        }
                    })
                    this.setState({
                        firstList,
                        secondList,
                        threeList
                    })
                }
            }
        })
    }

    // 选择一级分类
    selectFirst(categoryId) {
        const secondListShow = []
        const firstValue = categoryId
        if (categoryId) {
            this.state.secondList.forEach(item => {
                const reg = new RegExp(`^${categoryId}`)
                if (reg.test(item.categoryId)) {
                    secondListShow.push(item)
                }
            })
        }
        this.setState({
            secondListShow,
            threeListShow: [],
            firstValue,
            secondValue: undefined,
            threeValue: undefined
        })
    }

    // 选择二级分类
    selectSecond(categoryId) {
        const threeListShow = []
        const secondValue = categoryId
        if (categoryId) {
            this.state.threeList.forEach(item => {
                const reg = new RegExp(`^${categoryId}`)
                if (reg.test(item.categoryId)) {
                    threeListShow.push(item)
                }
            })
        }
        this.setState({
            threeListShow,
            secondValue,
            threeValue: undefined
        })
    }

    // 选择三级分类
    selectThree(categoryId) {
        this.setState({
            threeValue: categoryId
        })
    }

    // 获取关联分类列表
    getRelationCategoriesList() {
        $.ajax({
            url: `${config.JuseProduct}/categories/getRelationCategoriesList`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                categoryId: this.state.threeValue || this.state.secondValue || this.state.firstValue
            },
            success: res => {
                console.log('获取关联分类列表', res)
                if (res.code === 200) {
                    res.data.forEach(item => {
                        item.key = item.categoryShowId
                    })
                    this.setState({
                        tableList: res.data
                    })
                }
            }
        })
    }

    // 条件查询
    search() {
        this.getRelationCategoriesList()
    }

    // 重置查询
    reset() {
        this.setState({
            firstValue: undefined,
            secondValue: undefined,
            threeValue: undefined,
            secondListShow: [],
            threeListShow: []
        }, () => {
            this.getRelationCategoriesList()
        })
    }

    // 获取关联分类树
    getRelationCategoriesTree(callback) {
        $.ajax({
            url: `${config.JuseProduct}/categories/getRelationCategoriesTree`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            success: res => {
                console.log('获取关联分类树', res)
                if (res.code === 200) {
                    this.setState({
                        tree: res.data.tree,
                        list: res.data.list,
                        showTree: res.data.showTree,
                        showList: res.data.showList,
                        relationList: res.data.relationList
                    })
                    if (callback) {
                        callback.call(this)
                    }
                }
            }
        })
    }

    // 显示新增模态框
    showAdd() {
        this.getRelationCategoriesTree()
        this.setState({
            addVisible: true,
            showCheckedKeys: [],
            checkedKeys: [],
            expandedKeys: []
        })
    }

    // 生成前端分类树形组件
    setShowTree() {
        const loop = item => {
            return <TreeNode title={item.categoryName} key={item.categoryId}>
                {item.son && item.son.map(value => {
                    return loop(value)
                })}
            </TreeNode>
        }
        return this.state.showTree.map(item => {
            return loop(item)
        })
    }

    // 生成后端分类树形组件
    setTree() {
        const loop = item => {
            const title = item.Rename || item.categoryName
            return <TreeNode title={title} key={item.categoryId}>
                {item.son && item.son.map(value => {
                    return loop(value)
                })}
            </TreeNode>
        }
        return this.state.tree.map(item => {
            return loop(item)
        })
    }

    // 选择前端分类
    selectShowCategory(obj, e) {
        const showCheckedKeys = []
        const checkedKeys = []
        const expandedKeys = []
        if (e.checked) {
            const checkedId = obj.checked.pop()
            showCheckedKeys.push(checkedId)
            this.state.relationList.forEach(item => {
                if (item.categoryShowId === checkedId) {
                    checkedKeys.push(item.categoryId)
                }
            })
            this.state.list.forEach(item => {
                checkedKeys.forEach(value => {
                    if (value.includes(item.categoryId)) {
                        expandedKeys.push(item.categoryId)
                    }
                })
            })
        }
        this.setState({
            showCheckedKeys,
            checkedKeys,
            expandedKeys
        })
    }

    // 选择后端分类
    selectCategory(obj, e) {
        const { checkedKeys, list } = this.state
        if (e.checked) {
            const checkedId = obj.checked.pop()
            list.forEach(item => {
                const reg = new RegExp(`^${checkedId}`)
                if (reg.test(item.categoryId)) {
                    checkedKeys.push(item.categoryId)
                }
            })
        } else {
            let delIndex
            checkedKeys.forEach((item, index) => {
                if (!obj.checked.includes(item)) {
                    delIndex = index
                }
            })
            checkedKeys.splice(delIndex, 1)
        }
        this.setState({
            checkedKeys: [...new Set(checkedKeys)]
        })
    }

    // 新增关联分类
    addRelationCategories() {
        const { showCheckedKeys, checkedKeys } = this.state
        if (!showCheckedKeys.length || !checkedKeys.length) {
            return message.error('请选择分类！')
        }
        $.ajax({
            url: `${config.JuseProduct}/categories/addRelationCategories`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                categoryShowId: showCheckedKeys[0],
                categoryId: checkedKeys
            },
            success: res => {
                console.log('新增关联分类', res)
                let error
                if (res.code === 200) {
                    this.setState({
                        addVisible: false
                    })
                    return this.getRelationCategoriesList()
                } else if (res.code == 201) {
                    error = '请选择分类！'
                } else if (res.code === 202) {
                    error = '该前端分类已被删除！请重新选择！'
                } else if (res.code === 203) {
                    error = '该前端分类已存在对应关系！请重新选择！'
                } else if (res.code === 204) {
                    error = '所选择的后端已被删除或未启用！请重新选择'
                }
                message.error(error)
            }
        })
    }

    // 隐藏新增模态框
    hiddenAdd() {
        this.setState({
            addVisible: false
        })
    }

    // 展开后端分类节点
    onExpand(expandedKeys, e) {
        console.log(expandedKeys, e.expanded)
        if (!e.expanded) {
            const list = this.state.expandedKeys
            let delIndex
            list.forEach((item, index) => {
                if (!expandedKeys.includes(item)) {
                    delIndex = index
                }
            })
            console.log(list, delIndex)
            const categoryId = list[delIndex]
            expandedKeys = expandedKeys.filter(item => {
                const reg = new RegExp(`^${categoryId}`)
                return !reg.test(item)
            })
        }
        this.setState({
            expandedKeys
        })
    }

    // 显示公共模态框
    showPublic(publicState) {
        this.state.selectedRowKeys.length && this.setState({
            publicState,
            publicVisible: true
        })
    }

    // 显示公共模态框标题
    showTitle() {
        const publicState = this.state.publicState
        let title = ''
        switch (publicState) {
            case 1:
                title = '删除'
                break
            case 2:
                title = '启用'
                break
            case 3:
                title = '停用'
                break
        }
        return title
    }

    // 隐藏公共模态框
    hiddenPublic() {
        this.setState({
            publicVisible: false
        })
    }

    // 公共模态框确定事件
    confirmPublic() {
        const categoryId = this.state.selectedRowKeys
        switch (this.state.publicState) {
            case 1:
                $.ajax({
                    url: `${config.JuseProduct}/categories/delRelationCategories`,
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: {
                        categoryId
                    },
                    success: res => {
                        console.log('删除前端分类与后端分类对应关系', res)
                        if (res.code === 200) {
                            if (res.mes) {
                                message.info(res.mes)
                            }
                            this.getRelationCategoriesList()
                            this.setState({
                                selectedRowKeys: []
                            })
                        }
                    }
                })
                break
            case 2:
                $.ajax({
                    url: `${config.JuseProduct}/categories/useRelationCategories`,
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: {
                        categoryId
                    },
                    success: res => {
                        console.log('启用前端分类与后端分类对应关系', res)
                        if (res.code === 200) {
                            this.getRelationCategoriesList()
                        }
                    }
                })
                break
            case 3:
                $.ajax({
                    url: `${config.JuseProduct}/categories/stopRelationCategories`,
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: {
                        categoryId
                    },
                    success: res => {
                        console.log('停用前端分类与后端分类对应关系', res)
                        if (res.code === 200) {
                            this.getRelationCategoriesList()
                        }
                    }
                })
                break
        }
        this.setState({
            publicVisible: false
        })
    }

    // 显示修改模态框
    showUpdate() {
        if (this.state.selectedRowKeys.length === 1) {
            this.getRelationCategoriesTree(() => {
                const categoryId = this.state.selectedRowKeys[0]
                const showCheckedKeys = [categoryId]
                let checkedKeys = []
                this.state.tableList.forEach(item => {
                    if (item.categoryShowId === categoryId) {
                        checkedKeys = item.relationList.map(value => value.categoryId)
                    }
                })
                const expandedKeys = []
                this.state.list.forEach(item => {
                    checkedKeys.forEach(value => {
                        if (value.includes(item.categoryId)) {
                            expandedKeys.push(item.categoryId)
                        }
                    })
                })
                this.setState({
                    updateVisible: true,
                    showCheckedKeys: [categoryId],
                    showExpandedKeys: [categoryId],
                    checkedKeys,
                    expandedKeys
                })
            })
        }
    }

    // 修改关联分类
    updateRelationCategories() {
        const { showCheckedKeys, checkedKeys } = this.state
        if (!showCheckedKeys.length || !checkedKeys.length) {
            return message.error('请选择分类！')
        }
        Modal.confirm({
            title: '确认是否修改该记录？',
            onOk: () => {
                $.ajax({
                    url: `${config.JuseProduct}/categories/updateRelationCategories`,
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: {
                        categoryShowId: showCheckedKeys[0],
                        categoryId: checkedKeys
                    },
                    success: res => {
                        console.log('修改关联分类', res)
                        let error
                        if (res.code === 200) {
                            this.setState({
                                updateVisible: false
                            })
                            return this.getRelationCategoriesList()
                        } else if (res.code == 201) {
                            error = '请选择分类！'
                        } else if (res.code === 202) {
                            error = '该前端分类已被删除！请重新选择！'
                        } else if (res.code === 203) {
                            error = '该前端分类不存在对应关系！请重新选择！'
                        } else if (res.code === 204) {
                            error = '所选择的后端已被删除或未启用！请重新选择'
                        } else if (res.code === 205) {
                            error = '已启用对应关系无法修改！请重新选择'
                        }
                        message.error(error)
                    }
                })
            }
        })
    }

    // 隐藏修改模态框
    hiddenUpdate() {
        this.setState({
            updateVisible: false
        })
    }

    // 生成修改前端分类树形组件
    setUpdateShowTree() {
        const categoryId = this.state.selectedRowKeys[0]
        const loop = item => {
            let disabled
            let disableCheckbox
            if (item.categoryId === categoryId) {
                disabled = false
                disableCheckbox = true
            } else {
                disabled = true
                disableCheckbox = false
            }
            return <TreeNode title={item.categoryName} key={item.categoryId} disabled={disabled} disableCheckbox={disableCheckbox}>
                {item.son && item.son.map(value => {
                    return loop(value)
                })}
            </TreeNode>
        }
        return this.state.showTree.map(item => {
            return loop(item)
        })
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys) => {
                this.setState({ selectedRowKeys });
            },
        };
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 },
            },
        };
        const columns = [{
            title: '前端分类',
            width: '40%',
            render(record) {
                return record.categoryRoute.map(item => {
                    return item.categoryName
                }).join('>')
            }
        }, {
            title: '后端分类',
            width: '40%',
            render(record) {
                return <div>
                    {
                        record.relationList.map((item, index) => {
                            return <p key={index}>
                                {
                                    item.categoryRoute.map(value => {
                                        return value.categoryName
                                    }).join('>')
                                }
                            </p>
                        })
                    }
                </div>
            }
        }, {
            title: '状态',
            width: '15%',
            render(record) {
                let text
                if (record.relationState === 0) {
                    text = '未启用'
                } else if (record.relationState === 1) {
                    text = '已启用'
                } else {
                    text = '已停用'
                }
                return text
            }
        }];
        return (
            <Form>
                <div className='goods-label' style={{ minWidth: 1250 }}>
                    <div className='goods-label-cont clearfix'>
                        <div className='goods-label-cont-nav clearfix'>
                            <Breadcrumb separator=">">
                                <Breadcrumb.Item>首页</Breadcrumb.Item>
                                <Breadcrumb.Item>商品管理</Breadcrumb.Item>
                                <Breadcrumb.Item>前端与后端分类对应管理</Breadcrumb.Item>
                            </Breadcrumb>
                        </div>
                        <div className='clearfix member-content-Search'>
                            <div className='addetd addetd-bb indtner  uogt-a'>
                                <InputGroup compact>
                                    <Input addonBefore="前端一级分类" />
                                    <Select
                                        style={{ width: 210, marginLeft: 45 }}
                                        placeholder='请选择'
                                        onChange={this.selectFirst.bind(this)}
                                        allowClear
                                        value={this.state.firstValue}
                                    >
                                        {
                                            this.state.firstList.map((item, index) => {
                                                return <Option key={index} value={item.categoryId}>
                                                    {item.categoryName}
                                                </Option>
                                            })
                                        }
                                    </Select>
                                </InputGroup>
                            </div>
                            <div className='addetd addetd-bb indtner uogt-a'>
                                <InputGroup compact>
                                    <Input addonBefore="前端二级分类" />
                                    <Select
                                        style={{ width: 210, marginLeft: 45 }}
                                        placeholder='请选择'
                                        onChange={this.selectSecond.bind(this)}
                                        allowClear
                                        value={this.state.secondValue}
                                    >
                                        {
                                            this.state.secondListShow.map((item, index) => {
                                                return <Option key={index} value={item.categoryId}>
                                                    {item.categoryName}
                                                </Option>
                                            })
                                        }
                                    </Select>
                                </InputGroup>
                            </div>
                            <div className='addetd addetd-bb indtner uogt-a'>
                                <InputGroup compact>
                                    <Input addonBefore="前端三级分类" />
                                    <Select
                                        style={{ width: 210, marginLeft: 45 }}
                                        placeholder='请选择'
                                        onChange={this.selectThree.bind(this)}
                                        allowClear
                                        value={this.state.threeValue}
                                    >
                                        {
                                            this.state.threeListShow.map((item, index) => {
                                                return <Option key={index} value={item.categoryId}>
                                                    {item.categoryName}
                                                </Option>
                                            })
                                        }
                                    </Select>
                                </InputGroup>
                            </div>
                            <Button type="primary" style={{ marginLeft: 50 }} className='member-button' icon="search" onClick={this.search.bind(this)}>查询</Button>
                            <Button type="primary" className='member-button' icon="reload" onClick={this.reset.bind(this)}>重置</Button>
                        </div>
                        <div className='clearfix'>
                            <div className='chengge-e'>
                                <Button className='member-button-aa' type='primary' onClick={this.showAdd.bind(this)} style={{ marginLeft: 20 }}>新增</Button>
                                <Button className='member-button-aa' type='primary' onClick={this.showUpdate.bind(this)}>修改</Button>
                                <Button className='member-button-aa' type='primary' onClick={this.showPublic.bind(this, 1)}>删除</Button>
                                <Button className='member-button-aa' type='primary' onClick={this.showPublic.bind(this, 2)}>启用</Button>
                                <Button className='member-button-aa' type='primary' onClick={this.showPublic.bind(this, 3)}>停用</Button>
                            </div>
                        </div>
                        <div className='clearfix backendt'>
                            <div className='allgoods-table clearfix'>
                                <Table
                                    rowSelection={rowSelection}
                                    columns={columns}
                                    dataSource={this.state.tableList}
                                    pagination={false}
                                    bordered
                                />
                            </div>
                        </div>
                    </div>
                    <Modal
                        title="新增对应关系"
                        visible={this.state.addVisible}
                        onOk={this.addRelationCategories.bind(this)}
                        onCancel={this.hiddenAdd.bind(this)}
                        width='700px'
                        maskClosable={false}
                    >
                        <div className='relationshipt'>
                            <div className='relationshipt_left'>
                                <p>前端分类：</p>
                                <Tree
                                    checkable
                                    onCheck={this.selectShowCategory.bind(this)}
                                    checkStrictly
                                    checkedKeys={this.state.showCheckedKeys}
                                >
                                    {this.setShowTree()}
                                </Tree>
                            </div>
                            <div className='relationshipt_right'>
                                <p>后端分类：</p>
                                <Tree
                                    checkable
                                    onCheck={this.selectCategory.bind(this)}
                                    checkStrictly
                                    checkedKeys={this.state.checkedKeys}
                                    onExpand={this.onExpand.bind(this)}
                                    expandedKeys={this.state.expandedKeys}
                                >
                                    {this.setTree()}
                                </Tree>
                            </div>
                        </div>
                    </Modal>
                    <Modal
                        title="修改对应关系"
                        visible={this.state.updateVisible}
                        onOk={this.updateRelationCategories.bind(this)}
                        onCancel={this.hiddenUpdate.bind(this)}
                        width='700px'
                        maskClosable={false}
                    >
                        <div className='relationshipt'>
                            <div className='relationshipt_left'>
                                <p>前端分类：</p>
                                <Tree
                                    checkable
                                    onCheck={this.selectShowCategory.bind(this)}
                                    checkStrictly
                                    checkedKeys={this.state.showCheckedKeys}
                                    expandedKeys={this.state.showExpandedKeys}
                                >
                                    {this.setUpdateShowTree()}
                                </Tree>
                            </div>
                            <div className='relationshipt_right'>
                                <p>后端分类：</p>
                                <Tree
                                    checkable
                                    onCheck={this.selectCategory.bind(this)}
                                    checkStrictly
                                    checkedKeys={this.state.checkedKeys}
                                    onExpand={this.onExpand.bind(this)}
                                    expandedKeys={this.state.expandedKeys}
                                >
                                    {this.setTree()}
                                </Tree>
                            </div>
                        </div>
                    </Modal>
                    <Modal
                        title={this.showTitle()}
                        visible={this.state.publicVisible}
                        onOk={this.confirmPublic.bind(this)}
                        onCancel={this.hiddenPublic.bind(this)}
                        maskClosable={false}
                    >
                        <div className='detleti'>
                            {this.state.publicState === 1 && <p>确认是否删除前、后端分类的对应关系？</p>}
                            {this.state.publicState === 2 && <p>确认是否启用前、后端分类的对应关系？</p>}
                            {this.state.publicState === 3 && <p>确认是否停用前、后端分类的对应关系？</p>}
                        </div>
                    </Modal>
                </div>
            </Form>
        )
    }
}

const FrontAndBack = Form.create()(frontAndBackForm);
export default FrontAndBack;